package logic

import (
	"cart_srv/cache"
	"cart_srv/models"
	"context"
	"errors"

	"cart_srv/cart"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	var g models.Goods
	g.ID = uint(in.GoodsId)
	err := g.ShowGoods()
	if err != nil {
		logx.Error("购物车添加失败:商品查找失败:", err)
		return nil, err
	}
	if g.Stock < int(in.Num) {
		logx.Error("购物车添加失败:商品", errors.New("库存不足"))
		return nil, errors.New("库存不足")
	}

	//查询购物车 是否存在商品
	if cache.ExistsCart(in.UserId, in.GoodsId) {
		err = cache.UpdateCartNum(in.UserId, in.GoodsId, in.Num)
	} else {
		//不存在,添加
		goodsMap := map[string]interface{}{
			"Title": g.Title,
			"Price": g.Price,
			"Num":   in.Num,
		}

		err = cache.AddCart(in.UserId, in.GoodsId, goodsMap)
		if err != nil {
			logx.Error("购物车添加失败:", err)
			return nil, err
		}
	}

	return &cart.AddCartResponse{}, nil
}
